package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heima.article.dto.ArticleDto;
import com.heima.article.entity.ApArticle;
import com.heima.article.entity.ApArticleContent;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.IApArticleContentService;
import com.heima.article.service.IApArticleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.ResponseResult;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 文章信息表，存储已发布的文章 服务实现类
 * </p>
 *
 * @author syl
 * @since 2022-11-17
 */
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements IApArticleService {


    @Autowired
    private IApArticleContentService apArticleContentService;

    @Override
    public ResponseResult<Long> saveApArticle(ArticleDto dto) {
        if(dto.getId() == null){
            ApArticle apArticle = new ApArticle();
            BeanUtils.copyProperties(dto,apArticle);
            apArticle.setCreatedTime(new Date());
            this.save(apArticle);
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(dto.getContent());
            apArticleContentService.save(apArticleContent);
            return ResponseResult.okResult(apArticle.getId());
        }else{
            ApArticle apArticle = new ApArticle();
            BeanUtils.copyProperties(dto,apArticle);
            this.updateById(apArticle);
            LambdaUpdateWrapper<ApArticleContent> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(ApArticleContent::getContent,dto.getContent());
            updateWrapper.eq(ApArticleContent::getArticleId,apArticle.getId());
            apArticleContentService.update(updateWrapper);
            return ResponseResult.okResult(apArticle.getId());
        }
    }
}
